<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class OxArticle 
{
	public $idarticle;
	public $title;
	public $article_abstract;
	public $content;
	public $idstory; //story object
    /* @var $story OxStory */
	public $story; //story object
    /* @var $user OxUser */
	public $user; //user object
	public $organizationrole; //organization role object
    /* @var $organization OxOrganization */
	public $organization; //organization role object
	public $timepublished;
	public $timestamp;
	public $devtag; //free text for development purpose only
	public $signature;
	public $signature_style; 
	/* @var $geostamps OxGeostamp */
	public $geostamps;
	public $tags;
	public $peopletags;
	public $related_articles;
    public $links;
	
	public $score;
	
	public $flag_types;
	public $all_flags_locked;
	
	public $published_status;
		const published_status_not_published = 0; //being wrtten, still not published (if ever will be)
		const published_status_published = 1; //published. Only this one is visible to others and to search.
		const published_status_suspended = 2; //temporarily suspended by moderator, pending decision. Visible only by author.
		const published_status_removed = 3; //permanently removed by moderator. Only the fact that this article exists is visible to author.

    public $action_pending;
    private $flags_points_overview;
    private $flags_points_overview_read;
    
	private $CI;
		
    public static function from_id($article_id)
    {
        $new_article = new OxArticle();
        $new_article->load($article_id);
        return $new_article;
    }
    
    public static function get_random_article()
    {
        $new_article = new OxArticle();
        $new_article->load('random');
        return $new_article;
    }
    public static function get_random_articles($count)
    {
        $a = array();
        for($i=0;$i<$count;$i++)
        {
            $new_article = new OxArticle();
            $new_article->load('random');
            $a[] = $new_article;
        }
        return $a;
    }
    
    function __construct($user = null)
    {
		$this->clear($user);
	}
	
	function clear($user = null)
	{
		$this->CI =& get_instance();
	
		$this->idarticle = 0;

		$this->title = "";
		$this->article_abstract = "";
		$this->content = "";
		$this->idstory = 0; //story object
		$this->story = null; //story object
		$this->user  = ($user?OxUser::from_id($user->iduser):new OxUser()); //user object
		$this->organizationrole = null; //organization role object
		$this->organization = null;
		$this->timepublished = null;
		$this->timestamp = null;
		$this->devtag = null; //free text for development purpose only
		$this->signature = "";
		$this->signature_style = 1;
		$this->geostamps = array();
		$this->tags = array();
		$this->peopletags = array();
		$this->related_articles = array();
		
		$this->score = 0;
		
		$this->flag_types = array();
		$this->all_flags_locked = FALSE;
		$this->published_status = 0;
        
        $this->action_pending = false;
        $this->flags_points_overview = array();
        $this->flags_points_overview_read = false;
    }
	
	private function update_member($name, $article_data)
	{
		$fullname = 'article_'.$name;
		if(isset($article_data[$fullname]))
		{
			$this->$name = $article_data[$fullname];
		}
	}
	
	function update($article_data)
	{
        /*
		echo 'post as it came: ';
		print_r($_POST);
		
		echo 'current object id: '.$this->idarticle;
		*/
		if(!$article_data['article_idarticle'])
		{
			//echo 'new article creating';
			$this->clear();
		}
		else
		{
			if($article_data['article_idarticle'] != $this->idarticle)
			{
				//echo 'will update existing article';
				$this->load($article_data['article_idarticle']);
			}
		}
		
		$this->update_member('title', $article_data);
		$this->update_member('content', $article_data);
		$this->update_member('signature', $article_data);
		$this->update_member('timestamp', $article_data);
        
		if(isset($article_data['article_abstract']))
		{
			$this->article_abstract = $article_data['article_abstract'];
		} 
        
        $s = $article_data['article_signature_style'];
        
        $st = $s[0];
        
        $this->signature_style = $st;
        
        if($st > 3)
        {
            //Here decide the oranization and role
            $org = substr ( $s , 1);
            $this->organization = OxOrganization::from_id($org);
            
            $query = $this->CI->db->get_where('organizations_users', array('iduser' => $this->user->iduser,
                'idorganization' => $this->organization->idorganization))->result();
            
            $this->organizationrole = $query[0];
        }
    }

    function load($id, $load_child_objects = true, $load_related_tags = false)
	{
		$this->clear();
        if($id == 'random')
        {
            $this->CI->db->order_by("RAND()", "desc"); 
            $query = $this->CI->db->get('articles', 1);            
        }
        else
        {
            $query = $this->CI->db->get_where('articles', 'idarticle = ' . $id);
        }
		$temp = $query->result();
		$artcle_data = $temp[0];
		
		$this->idarticle = $artcle_data->idarticle;
		$this->title = $artcle_data->title;
		$this->article_abstract = $artcle_data->abstract;
		$this->content = $artcle_data->content;
		
        $this->user = OxUser::from_id($artcle_data->iduser);
  		
		//get the story
        
        $this->idstory = $artcle_data->idstory;
        $count_story_articles = $this->CI->db->select('count(distinct idarticle) as article_count')
                      ->from('articles')
                      ->where('idstory', $this->idstory)
                      ->get()->result();
        
        if($count_story_articles[0]->article_count > 1)
        {
            $this->story = OxStory::from_id($this->idstory);
        }
        else
        {
            $this->story = null;
        }
       
		//get the organization and role
		if($artcle_data->idorganizationrole)
		{
			$query = $this->CI->db->get_where('organizations_users', 'idorganizations_users = ' . $artcle_data->idorganizationrole);
			$res = $query->result();
			$this->organizationrole = $res[0];
			
			$this->organization = OxOrganization::from_id($this->organizationrole->idorganization);
		}
		else
		{
			$this->organizationrole = null;
			$this->organization = null;
		}
		
		$this->timepublished = $artcle_data->timepublished;
		$this->timestamp = $artcle_data->timestamp;
		$this->devtag = $artcle_data->tag; //free text for development purpose only
		$this->signature = $artcle_data->signature;
		$this->signature_style = $artcle_data->signature_style;
		$this->geostamps = array();
		$this->tags = array();
		$this->related_articles = array();
		
		if($load_child_objects)
		{
			//load tags
			$query = $this->CI->db->select("tags.*")
				->from('articles_tags')
				->join('tags', 'articles_tags.idtags = tags.idtags')
				->where('idarticle', $this->idarticle)
				->get();
			$this->tags = $query->result();
			
			//load peopletags
			$query = $this->CI->db->select("people.*")
				->from('articles_peopletags')
				->join('people', 'articles_peopletags.idpeople = people.idpeople')
				->where('idarticle', $this->idarticle)
				->get();
			$this->peopletags = $query->result();
			
			//load geolocations
			$query = $this->CI->db->select("geonameid")
                                  ->from('articles_geostamps')
                                  ->where('idarticle', $this->idarticle)
                                  ->get()->result();
            foreach($query as $stampid)
            {
                $this->geostamps[] = OxGeostamp::from_id($stampid->geonameid);
            }

			//load relateed articles
			$query = $this->CI->db->select("articles_relations.*")->select("articles.idarticle")
															  ->select("articles.title")
															  ->select("articles.abstract")
				->from('articles_relations')
				->join('articles', 'articles_relations.idarticle_related = articles.idarticle')
				->where('articles_relations.idarticle_main', $this->idarticle)
				->order_by('articles_relations.relation_type')
				->get();
			$this->related_articles = $query->result();
                        
			//load relateed articles
			$query = $this->CI->db->select("articles_links.*")
                				  ->from('articles_links')
                                  ->where('articles_links.idarticle', $this->idarticle)
                                  ->get();
			$this->links = $query->result();
		}
		
		$this->score = $artcle_data->score;
		
		$this->flag_types = array();
		$this->all_flags_locked = $artcle_data->all_flags_locked;
		$this->published_status = $artcle_data->published_status;
		/*
		echo "<!-- OxArticle: ";
		print_r($this);
		echo "-->";
		*/
	}

	function taglist($sep)
	{
		$list = "";
		foreach($this->tags as $tag)
		{
			if($list)
			{
				$list .= $sep;
			}
			$list .= $tag->name;
                        $list .= ' <a href="javascript:remove_tag('.$tag->idtags.')">(remove)</a>';
		}
		return $list;
	}
	
	function peopletaglist($sep)
	{
		$list = "";
		foreach($this->peopletags as $peopletag)
		{
			if($list)
			{
				$list .= $sep;
			}
			$list .= $peopletag->name;
                        $list .= ' <a href="javascript:remove_peopletag('.$peopletag->idpeople.')">(remove)</a>';
		}
		return $list;
	}
	
	function geostamplist($sep, $show_remove = true)
	{
		$list = "";
		foreach($this->geostamps as $geostamp)
		{
			if($list)
			{
				$list .= $sep;
			}
			$list .= $this->CI->geodata->show($geostamp);
            if($show_remove)
            {
                $list .= ' <a href="javascript:remove_geostamp('.$geostamp->geonameid.')">(remove)</a>';
            }
		}
		return $list;
	}	
    
    function linkslist($sep)
	{
		$list = "";
		foreach($this->links as $articlelink)
		{
			if($list)
			{
				$list .= $sep;
			}
			$list .= '<a href="' . prep_url($articlelink->url) . '" TARGET="_blank">';
            if($articlelink->text)
            {
                $list .= $articlelink->text;
            }
            else
            {
                $list .= $articlelink->url;
            }            
            $list .= '</a>';
            $list .= ' <a href="javascript:remove_link('.$articlelink->idarticles_links.')">(remove)</a>';
		}
		return $list;
	}	
	
	function rel_article_list($sep)
	{
		$list = "";
		foreach($this->related_articles as $related_article)
		{
			if($list)
			{
				$list .= $sep;
			}
			$list .= $related_article->title;
            if($this->CI->articles->relation_text($related_article->relation_type))
            {
                $list .= " (" . $this->CI->articles->relation_text($related_article->relation_type) . ")";
            }    
            $list .= ' <a href="javascript:remove_related_article('.$related_article->idarticles_relations.')"> (remove)</a>';            
		}
		return $list;
	}
	
	function save()
	{
		if($this->idarticle)
		{
                    //update
                    $this->CI->db
                         ->set('title', $this->title)
                         ->set('abstract', $this->article_abstract)
                         ->set('content', $this->content)
                         ->set('timestamp', $this->timestamp)
                         ->set('timepublished', 'now()', false)
                         ->set('signature', $this->signature)
                         ->set('signature_style', $this->signature_style)
                         ->set('idorganizationrole', ($this->organizationrole 
                                                        ? $this->organizationrole->idorganizations_users 
                                                        : null) )
                         ->where('idarticle', $this->idarticle)
                         ->update('articles');
		}
		else
		{
			//insert new
			// mark the user
			$this->user = OxUser::from_id($this->CI->session->current_user()->iduser);
			// check/create the story
			if(!$this->story)
			{
				$this->story = $this->create_new_story($this->title);
			}
			// check geostamps (later)
			// check tags (later)
			// check related articles (later)
			
            try
            {
			// insert
			$this->CI->db->set('title', $this->title)
						 ->set('content', $this->content)
						 ->set('iduser', $this->user->iduser)
						 ->set('idstory', $this->story->idstory)
						 ->set('abstract', $this->article_abstract)
						 ->set('timestamp', $this->timestamp)
						 ->set('timepublished', 'now()', false)
						 ->set('signature', $this->signature)
						 ->insert('articles');
            } catch (Exception $Ex)
            {
                echo 'blah';
            }
			// retrieve the ID
			$query = $this->CI->db->query('SELECT LAST_INSERT_ID()');
			$row = $query->row_array();
			$this->idarticle = $row['LAST_INSERT_ID()'];
		}
	}
	
	private function create_new_story($title)
	{
		// insert
		$this->CI->db->set('title', $this->title)
					 ->insert('stories');
		
		// retrieve the ID
		$query = $this->CI->db->query('SELECT LAST_INSERT_ID()');
		$row = $query->row_array();
		$story = (object) array('idstory' => $row['LAST_INSERT_ID()'],
					   'title' => $title);
		return $story;
	}
    
    public function add_tag($id_tag)
    {
		$this->CI->db->set('idarticle', $this->idarticle)
					 ->set('idtags', $id_tag)
                     ->insert('articles_tags');
    }
    public function remove_tag($id_tag)
    {
		$this->CI->db->delete('articles_tags', 
                        array('idarticle' => $this->idarticle,
                            'idtags' => $id_tag)); ;
    }     
    public function add_peopletag($id_peopletag)
    {
		$this->CI->db->set('idarticle', $this->idarticle)
					 ->set('idpeople', $id_peopletag)
                     ->insert('articles_peopletags');
    }
    public function remove_peopletag($id_peopletag)
    {
		$this->CI->db->delete('articles_peopletags', 
                        array('idarticle' => $this->idarticle,
                            'idpeople' => $id_peopletag)); ;
    }     
    public function add_geolocation($geonameid)
    {
		$this->CI->db->set('idarticle', $this->idarticle)
					 ->set('geonameid', $geonameid)
                     ->insert('articles_geostamps');
    }
    public function remove_geolocation($geonameid)
    {
		$this->CI->db->delete('articles_geostamps', 
                        array('idarticle' => $this->idarticle,
                            'geonameid' => $geonameid)); ;
    }  
    public function add_new_link($url, $text)
    {
		$this->CI->db->set('idarticle', $this->idarticle)
					 ->set('url', $url)
                     ->set('text', $text)
                     ->insert('articles_links');
    }
    public function remove_link($linkid)
    {
		$this->CI->db->delete('articles_links', 
                        array('idarticles_links' => $linkid));
    }  
    function add_new_related_article($article_relation_type, $related_article_id)    
    {
		$this->CI->db->set('idarticle_main', $this->idarticle)
					 ->set('idarticle_related', $related_article_id)
                     ->set('relation_type', $article_relation_type)
                     ->insert('articles_relations'); 
        /*
        if($article_relation_type > 0)
        {
            $related_article_query = $this->CI->db->select('idstory')
                                         ->from('articles')
                                         ->where('idarticle', $related_article_id)
                                         ->get()->result();
            
            $this->CI->db->set('idstory', $related_article_query[0]->idstory)
                     ->where('idarticle',$this->idarticle)
                     ->update('articles'); 
        }
         * 
         */
    }    
    function remove_related_article($articleIdToRemove)   
    {
        $this->CI->db->delete('articles_relations', 
                array('idarticles_relations' => $articleIdToRemove));
    }
    function add_to_this_story($id_of_an_article_in_the_story)    
    {
        $related_article_query = $this->CI->db->select('idstory')
                                     ->from('articles')
                                     ->where('idarticle', $id_of_an_article_in_the_story)
                                     ->get()->result();

        $this->CI->db->set('idstory', $related_article_query[0]->idstory)
                 ->where('idarticle',$this->idarticle)
                 ->update('articles'); 
    }    
    
    ////////////////////////////////////////////////////////////////////////////////
    // Following are article viewing functions. They all take first parameter an
    // object of class oxarticle, which needs to be loaded prior to calling these
    // functions. Other parameters are view parameters, deciding what is shown and 
    // what is a link and to where

	function info($relevance = false, $show_signature_as_title_by_signature = true,
            $show_score_and_flag_bar = true, $show_timestamp = true, $show_geostamp = true, $show_signature = true,
            $style = '', $story_info = true)
	{
		$text = '<div class="article_preview"';
        if($style)
        {
            $text .= ' style="' . $style . '"';
        }
        $text .= '>';
        if($show_score_and_flag_bar)
        {
            $text .= '<div class="article_preview_stamp">'.$this->score_info().'</div>';
        }
        if($show_signature_as_title_by_signature)
        {
            $text .= '<b>'.$this->article_title_link().'</b> by '.
                    '<div class="article_preview_signature">'.$this->writer_link().'</div>';
        }
        else 
        {
            if($show_signature)
            {
                $text .= '<div class="article_preview_signature">'.$this->writer_link().'</div>';
            }
            $text .= '<h1>'.$this->article_title_link().'</h1>';
        }
        
        if($story_info && $this->story)
        {
            $text .= '<div class="article_preview_story_info">Part of ' . $this->story_title_link() . '</div>';
        }
        
        if($show_geostamp && $this->geostamps)
        {
            $text .= '<div class="article_preview_stamping">'.$this->geostamplist("; ", false);
            if($show_timestamp)
            {
                $text .= '; '.date("d-M-y",strtotime($this->timestamp));
            }
            $text.='</div>';
        }
        else 
        {
            if($show_timestamp)
            {
                $text .= '<div class="article_preview_stamping">'.date("d-M-y",strtotime($this->timestamp)).'</div>';
            }
        }
                    
        $text .= '</div>';
		return $text;		
        
    }

	function preview($show_tags = false, $show_signature = true)
	{
        $text = '<div class="article_preview">';
        $text .= '<div class="article_preview_stamp">'.$this->score_info().'</div>';
        if($show_signature)
        {
            $text .= '<div class="article_preview_signature">'.$this->writer_link().'</div>';
        }
        $text .= '<h1>'.$this->article_title_link().'</h1>';
        if($this->story)
        {
            $text .= '<div class="article_preview_story_info">Part of ' . $this->story_title_link() . '</div>';
        }
        if($this->geostamps)
        {
            $text .= '<div class="article_preview_stamping">'.$this->geostamplist("; ", false)
                    . '; '.date("d-M-y",strtotime($this->timestamp)).'</div>';
        }
        else
        {
            $text .= '<div class="article_preview_stamping">'.date("d-M-y",strtotime($this->timestamp)).'</div>';            
        }
        
        if($show_tags)
        {
            $text .= $this->tag_bar();
        }
        
        //prepare abstract
        $a = $this->article_abstract;
        
        if(strlen($a) < 5)
        {
            if(strlen($this->content) < 350)
            {
                $a = $this->content;
            }
            else
            {
                // calculate the length fo that yo udo not cut the whole word. 
                // Break between 250 and 350 where you find the first of following: . \n : ; , - space
                // if none is found, break on 275.

                $seps = array('.', '\n', ':', ';', ',', '-', ' ');
                $haystack = strrev(substr($this->content, 250, 100));

                $pos = -1;
                
                foreach($seps as $sep)
                {
                    $pos = strpos($haystack, $sep);
                    if($pos !== FALSE)
                    {
                        break;
                    }                    
                }
                
                if($pos != -1)
                {
                    $a = substr($this->content, 0, 350 - $pos);
                }
                else
                {
                    $a = substr($this->content, 0, 250);
                }
            }
        }
        $a = str_replace("<br/>","", $a);
        
        $text .= $a;
        $text .= '</div>';
		return $text;		
	}
    
    function show()
    {
        /*
        Timestamp(s), Geostamp(s)
        Score, flags info, relevance (if appropriate)
        Signature
        Title
        Tags
        Story info
        Content
            Text (only this for 0.3)
            pictures
            info blocks
            Info links
            Multimedia 
        See also links
        Related articles
        Documents
        Boost, message to author and flag action buttons 
        */
        $text = '<div class="article_preview article_show">';
        $text .= '<div id="" class="article_preview_stamp">'.$this->score_info().'</div>';

        $text .= '<div class="article_preview_signature">'.$this->writer_link().'</div>';
        $text .= '<h1>'.$this->article_title_link().'</h1>';
        if($this->story)
        {
            $text .= '<div class="article_preview_story_info">Part of ' . $this->story_title_link() . '</div>';
        }
        if($this->geostamps)
        {
            $text .= '<div class="article_preview_stamping">'.$this->geostamplist("; ", false)
                    . '; '.date("d-M-y",strtotime($this->timestamp)).'</div>';
        }
        else
        {
            $text .= '<div class="article_preview_stamping">'.date("d-M-y",strtotime($this->timestamp)).'</div>';            
        }
        $text .= $this->tag_bar();
        
        //Prepare content
        $c = str_replace("\n", "<br/>", $this->content);
        
        
        $text .= '<div>'.$c.'</div>';
        /*
            See also links
            Related articles
            Documents
            Boost, message to author and flag action buttons 
        */   
        $text .=
        '<div style="margin-top: 10px; float: right;"><input id="boost_button" type=button value="Boost!" onclick="voteArticleUp('. ((isset($this->idarticle))?$this->idarticle:'').')"/>
        <input type=button value="Flag!" onclick="showFlagDialog();"/>
        <input type=button value="Contact Author" onclick=""/>
        <input type=button value="Build the story" onclick=""/>
        <input type=button value="Email a friend" onclick=""/>
        </div>';
        
        if($this->related_articles)
        {
            $text .= '<div class="article_preview_see_also"><h2>See also:</h2>';
            foreach($this->related_articles as $rel_article)
            {
                
                $text .= '<div class="article_preview_see_also_link">';
                $text .= OxArticle::from_id($rel_article->idarticle_related)
                        //->info($relevance, $show_signature_as_title_by_signature, $show_score_and_flag_bar, $show_timestamp, $show_geostamp, $show_signature, $style)
                        ->info(false, true, true, true, true, true, 'border: none;');
                $text .= '</div>';
            }
            $text .= '</div>';
        }
        
        
        if($this->links)
        {
            $text .= '<div class="article_preview_see_also"><h2>External links:</h2>';
            foreach($this->links as $ext_link)
            {
                $text .= '<div class="article_preview_see_also_link">';
                $text .= '<a href="' . $ext_link->url . '" target="_blank">';
                $text .= ($ext_link->text?$ext_link->text:$ext_link->url);
                $text .= '</a></div>';
            }
            $text .= '</div>';
        }

        $text .= '</div>';//Final div closing, this must be right before return.
        return $text;		
        
    }
    
    /////////////////////////////////////////////////////////////////////////////
    // Functions used by viewing functions
    
  	function writer_link()
	{
        switch($this->signature_style)
        {
            case 0:
                return 'Anonymous author';
            case 1:
                return '<a href="' . site_url('profile/' . $this->user->iduser) . '">' .
					$this->user->name. '</a>';
            case 2:
                return '<a href="' . site_url('profile/' . $this->user->iduser) . '">' .
					$this->user->username. '</a>';            
            case 3:
                return '<a href="' . site_url('profile/' . $this->user->iduser) . '">' .
					$this->signature. '</a>';
            case 4:
                //return 'blah';
                return '<a href="' . site_url('profile/org/' . $this->organization->idorganization) . '">' .
					$this->organization->name. '</a>'; 
            case 5:
                //return 'blah';
                return '<a href="' . site_url('profile/' . $this->user->iduser) . '">' . $this->user->name. '</a>'
                    .', '.$this->organizationrole->role.', '
                    .'<a href="' . site_url('profile/org/' . $this->organization->idorganization) . '">' 
					.$this->organization->name. '</a>';                 
        }
	}
    
    function score_info()
	{
		if(isset($this->relevance) && $this->relevance)
		{
			return '<span id="scoreInfoBlock_'.$this->idarticle.'">Score: ' . $article->score .
					', target relevance: ' . $this->relevance . '</span>';
		}
		else
		{
			return '<span id="scoreInfoBlock_'.$this->idarticle.'">Score: ' . $this->score.'</span>';
		}
	}
	function article_title_link()
	{
		return '<a href="' . site_url('article/' . $this->idarticle) . '">' .
					$this->title . '</a>';
	}
	function story_title_link()
	{
        if($this->story)
        {
            return '<a href="' . site_url('story/' . $this->idstory) . '">' .
                        $this->story->title . '</a>';
        }
        else
        {
            return '';
        }
	}
    function tag_bar()
    {
        if($this->tags)
        {
            $text = '<div class="article_preview_tags"><b>SubjectTags: </b>';
            $first = true;
            foreach($this->tags as $tag)
            {
                if($first)
                {
                    $first = false;
                }
                else
                {
                    $text .= ', ';
                }
                $text .= $tag->name;
            }
            $text .= '</div>';
            return $text;
        }
        else
        {
            return '';
        }
    }
        
    public function flags()
    {
        if(!$this->flags_points_overview_read)
        {
            $CI =& get_instance();
            $this->flags_points_overview = $CI->articles->get_flags_for_article($this);
            $this->actions_read = true;
        }
        return $this->flags_points_overview;
    }
}

/* End of file OxArticle.php */